package chaowan.Controller;

import chaowan.Service.GoodsCategoryService;
import chaowan.Service.GoodsService;
import chaowan.pojo.Goods;
import chaowan.pojo.GoodsCategory;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Resource
    private GoodsService goodsService;
    @Resource
    private GoodsCategoryService goodsCategoryService;


    @GetMapping("/frontList")
    public String frontList(Model model) {
        List<Goods> goodsList = goodsService.findAll();
        model.addAttribute("goodsList", goodsList);
        List<GoodsCategory> categoryList = goodsCategoryService.list();
        model.addAttribute("categoryList", categoryList);
        return "good_list";
    }


    @GetMapping("/list")
    public String list(Model model) {
        List<Goods> goodsList = goodsService.findAll();
        model.addAttribute("goodsList", goodsList);
        return "goods/list";
    }

    @PostMapping("/add")
    public String add(Goods goods) {
        goodsService.save(goods);
        return "redirect:/goods/list";
    }
    @GetMapping("/editForm/{gid}")
    public String editForm(@PathVariable long gid, Model model) {
        Goods goods = goodsService.findById(gid);
        model.addAttribute("goods", goods);
        return "goods/edit";
    }

    @PostMapping("/update")
    public String update(Goods goods) {
        goodsService.update(goods);
        return "redirect:/goods/list";
    }

    @GetMapping("/delete/{gid}")
    public String delete(@PathVariable Long gid) {
        goodsService.deleteById(gid);
        return "redirect:/goods/list";
    }


    @GetMapping("/search")
    public String search(@RequestParam String keyword, Model model) {
        List<Goods> goodsList = goodsService.searchByKeyword(keyword);
        model.addAttribute("goodsList", goodsList);
        return "good_list";
    }

    @GetMapping("/addForm")
    public String addForm(Model model) {
        List<GoodsCategory> categoryList = goodsCategoryService.list();
        model.addAttribute("categoryList", categoryList);
        model.addAttribute("goods", new Goods());
        return "goods/add";
    }

    @GetMapping("/listByCategory")
    public String listByCategory(@RequestParam(required = false) Long cid, Model model) {
        List<Goods> goodsList;
        if (cid != null) {
            goodsList = goodsService.findByCategoryId(cid);
        } else {
            goodsList = goodsService.findAll();
        }
        model.addAttribute("goodsList", goodsList);
        List<GoodsCategory> categoryList = goodsCategoryService.list();
        model.addAttribute("categoryList", categoryList);

        return "good_list";
    }

}